<template>
  <div id="message_box" class="content">
    <div class="title">
      <img :src="title.img" />
      <span>{{ title.name }}</span>
    </div>
    <div
      style="
        flex-grow: 1;
        display: flex;
        flex-direction: column;
        position: relative;
        padding-bottom: 85px;
        height: calc(100% - 85px);
      "
    >
      <div style="overflow: auto" id="message_list">
        <div :key="item.id" v-for="item in message" class="message">
          <div :class="item.role === 'user' ? 'right' : 'left'">
            <UserMessage :item="item" />
            <div class="role_img">
              <img
                :src="
                  item.role === 'user'
                    ? require('../../assets/Img/content/user.png')
                    : require('../../assets/Img/header/position.png')
                "
              />
            </div>

            <BotMessage :item="item" :Submit="Submit" />
            <Tip :item="item" :Submit="Submit" />
            <div v-if="item.role === 'assistant'" class="message_assistant">
              <div class="tip_title">
                <span>{{ item.title }}</span
                ><a><span>换一换</span><a-icon type="swap" /></a>
              </div>
              <div style="text-align: left"><a>猜你想问</a></div>
              <div class="tip_cont">
                <a-space style="display: flex; flex-wrap: wrap">
                  <div
                    v-for="text in item.texts"
                    :key="text"
                    class="tip_tag"
                    @click="Submit('tip', text)"
                  >
                    {{ text }}
                  </div>
                </a-space>
              </div>
            </div>
          </div>
        </div>
      </div>
      <div class="send">
        <a-textarea
          v-model="seachValue"
          placeholder="请输入文字"
          :auto-size="{ minRows: 1, maxRows: 5 }"
          class="textareaDemo"
          @keydown="handleKeyDown"  
        />
        <div class="submit">
          <a-space :size="5">
            <img src="../../assets/Img/content/audio.png" alt="" />
            <img
              src="../../assets/Img/content/Voice.png"
              alt=""
              @click="toggleRecording"
            />
            <!-- <a-icon type="audio" class="audioDemo"/>
            <a-icon type="audio" theme="twoTone" /> -->
            <a-button type="primary" @click="toggleRecording">{{
              recording ? "停止" : "录音"
            }}</a-button>
            <a-button type="primary" @click="Submit('Sub')">发送</a-button>
          </a-space>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import UserMessage from "./components/UserMessage.vue";
import BotMessage from "./components/BotMessage.vue";
import Tip from "./components/TipMessage.vue";
// import Atlas from '../Atlas.vue';
export default {
  name: "Messages",
  components: { UserMessage, Tip, BotMessage },
  data() {
    return {
      recording: false,
      mediaRecorder: null,
      isTextAreaFocused:false,
      title: {
        name: "智能文教",
        img: "https://img0.baidu.com/it/u=671112370,873229032&fm=253&fmt=auto&app=120&f=JPEG?w=500&h=500",
      },
      message: [
        {
          id: 1,
          role: "tip",
          isTextAreaFocused:false,
          texts: [
            "应对敌军xxx装备，我方有那些方案？",
            "应对敌军xxx装备，我方有那些方案？",
            "应对敌军xxx装备，我方有那些方案？",
            "应对敌军xxx装备，我方有那些方案？",
          ],
          title: "你好, 张参谋，我是知识问答助",
        },
        //  { id: 1, role: "assistant", texts: ["应对敌军xxx装备，我方有那些方案？", '应对敌军xxx装备，我方有那些方案？', '应对敌军xxx装备，我方有那些方案？', '应对敌军xxx装备，我方有那些方案？'], title: "你好, 张参谋，我是知识问答助" },
        {
          id: 2,
          role: "user",
          texts: [
            "你好j应对敌军xxx装备，我方有那些方案？应对敌军xxx装备，我方有那些方案？应对敌军xxx装备，我方有那些方案？应对敌军xxx装备，我方有那些方案？应对敌军xxx装备，我方有那些方案？应对敌军xxx装备，我方有那些方案？应对敌军xxx装备，我方有那些方案？应对敌军xxx装备，我方有那些方案？应对敌军xxx装备，我方有那些方案？应对敌军xxx装备，我方有那些方案？",
          ],
        },
        { id: 3, role: "bot", texts: ["你好我是机器人"] ,loading:true},
        {
          id: 4,
          role: "bot",
          texts: ["你好我是机器人"],
          guess: [
            "应对敌军xxx装备，我方有那些方案？",
            "应对敌军xxx装备，我方有那些方案？",
          ],
          atlas: true,
        },
      ],
      seachValue: "",
    };
  },
  created() {
    console.log(this.$router);
    this.title = {
      name: this.$router.currentRoute.name,
      img: this.$router.currentRoute.meta.icon,
    };
  },
  methods: {
    toggleRecording() {
      if (this.recording) {
        this.stopRecording();
      } else {
        this.startRecording();
      }
    },
    async startRecording() {
      let chunks = [];
      const stream = await navigator.mediaDevices.getUserMedia({ audio: true });
      this.mediaRecorder = new MediaRecorder(stream);
      //   this.mediaRecorder.setOutputFormat(
      //     this.mediaRecorder.OutputFormat.MPEG_4
      //   );
      this.mediaRecorder.ondataavailable = this.handleDataAvailable;

      this.mediaRecorder.start();
      this.recording = true;
    },
    stopRecording() {
      this.mediaRecorder.stop();
      this.recording = false;
    },
    handleDataAvailable(event) {
      console.log(event.data);
      //   let blob = new Blob(event.data, { type: event.type });
      //   console.log(blob);
    },
    handleKeyDown(event) {  
      // 检查是否按下了回车键  
      if (event.key === 'Enter' || event.keyCode === 13) {  
        // 执行你想要的操作  
        if (!event.shiftKey) {  
            // 阻止表单提交（如果输入框位于表单内）  
            this.Submit('Sub')
            event.preventDefault();  
        }
      }  
    },  
    Submit(type, text) {
      if (type === "tip") {
        this.seachValue = text;
        return;
      }
      if (!this.seachValue) {
        this.$message.error("请输入，内容不得为空");
        return;
      }
      const newList = this.message;
      newList.push({
        id: newList?.length,
        role: "user",
        texts: [this.seachValue.replace(/\n/g, '<br>')],
      });
      this.message = newList;
      this.seachValue = "";
      this.$nextTick(()=>{
        this.scrollToBottomSmoothly("message_list");
      })
      
    },
    scrollToBottomSmoothly(targetId) {
      const element = document.getElementById(targetId);
      element.scrollTop  = element.scrollHeight+100;
    },
  },
  watch: {
    $route: {
      handler(val, oldVal) {
        this.title.name = val.name;
        this.title.img = val.meta.icon;
      },
      deep: true,
    },
  },
};
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped lang="less">
.content {
  display: flex;
  flex-direction: column;
  height: 100%;
}

.title {
  height: 77px;
  display: flex;
  align-items: center;
  background: linear-gradient(90deg, #87b9fc 0.59%, #b3d0ff 100%);
  margin: 12px;

  img {
    width: 60px;
    height: 60px;
    margin: 0 20px;
    padding: 10px;
  }

  span {
    font-size: 26px;
    font-weight: 600;
  }
}

.message {
  display: flex;
  flex-direction: column;
  padding: 0 12px;
  flex-grow: 1;

  .left {
    display: flex;
    justify-content: left;
    margin-bottom: 40px;
  }

  .left_content {
    background-color: white;
    border-radius: 4px;
    text-align: start;
    padding: 16px;
    display: flex;
    align-items: center;
    box-shadow: 0px 0px 6px rgba(15, 15, 52, 0.17);
    word-break: break-all;
  }

  .right {
    display: flex;
    justify-content: right;
    margin-bottom: 40px;
  }

  .right > span {
    background-color: #0075ff;
    border-radius: 4px;
    text-align: start;
    padding: 16px;
    color: white;
    display: flex;
    align-items: center;
    word-break: break-all;
  }

  .role_img {
    width: 64px;
    border-radius: 50%;
    margin: 0px 14px;

    img {
      width: 64px;
      border-radius: 50%;
    }
  }
}

.message_tip {
  padding: 14px;
  border-radius: 4px;
  box-shadow: 0px 0px 6px rgba(15, 15, 52, 0.17);
  background-color: white;
}

.tip_title {
  display: flex;
  justify-content: space-between;

  span {
    font-size: 17px;
    font-weight: 600;
    margin-bottom: 0px;
  }

  a {
    margin-left: 40px;

    span {
      padding-right: 8px;
      font-size: 16px;
      font-weight: 500;
    }
  }
}

.tip_cont {
  display: flex;
}

.tip_tag {
  background: #f5f8ff;
  border-radius: 4px;
  white-space: nowrap;
  padding: 16px 22px;
  margin-bottom: 14px;
}

.send {
  display: flex;
  position: relative;
  justify-content: space-between;
  width: 80%;
  position: absolute;
  bottom: 30px;
  left: 10%;
  ::v-deep .textareaDemo {
    resize: none;
    padding: 16px;
    padding-right: 150px;
  }

  .submit {
    position: absolute;
    right: 10px;
    bottom: 10px;
  }
}

.left_tip {
  display: flex;
  align-items: center;
  margin-top: 8px;
  a {
    margin-right: 12px;
  }
}

.message_assistant {
  padding: 14px;
  border-radius: 4px;
  box-shadow: 0px 0px 6px rgba(15, 15, 52, 0.17);
  background-color: white;
}
</style>
